<script lang="ts">
import { Component, Vue, Watch } from 'vue-facing-decorator';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import UserLink from '@/pages/profile/component/UserLink.vue';
import { queryComment, deleteComment } from '@/api/comment/comment';
import type { CommentInfo } from '@/api/comment/comment';
import AdminNav from '../component/AdminNav.vue';

@Component({
  components: {
    AdminNav,
    UserLink,
  }
})
export default class AdminCommentPage extends Vue {
  query = {
    page: 1,
    pageSize: 10,
  };
  comments: { keyword: string, page: number; pageSize: number; comments: CommentInfo[]; total: number } | null = null;
  loading = false;
  dayjs = dayjs;

  get keyword() {
    return (this.$route.query.keyword || '') + '';
  }
  updateKeyword(keyword: string) {
    this.$router.replace({
      name: this.$route.name,
      params: this.$route.params,
      query: { ...this.$route.query, keyword: keyword.trim() },
    });
  }

  @Watch('keyword', { immediate: true })
  onKeywordChange(keyword: string) {
    if (keyword !== this.comments?.keyword) {
      this.update();
    }
  }
  @Watch('query', { deep: true })
  onQueryChange() {
    if (this.comments?.page !== this.query.page || this.comments?.pageSize !== this.query.pageSize) {
      this.update();
    }
  }

  async update() {
    const keyword = this.keyword, page = this.query.page, pageSize = this.query.pageSize;
    this.comments = { keyword, page, pageSize, total: 0, comments: [] };
    if (!this.keyword) return;
    this.loading = true;
    const resp = await queryComment(keyword, this.query.page, this.query.pageSize);
    if (keyword !== this.keyword || page !== this.query.page || pageSize !== this.query.pageSize) return;
    this.loading = false;
    if (resp.error != null) {
      ElMessage.error('搜索评论错误：' + resp.error);
      return;
    }
    Object.assign(this.comments, { keyword, page, pageSize }, resp.data);
  }

  getAvatarUrl(avatar: string | undefined | null) {
    if (!avatar) return '/img/avatar.png';
    return '/api/image/' + avatar;
  }

  async handleDeleteComment(comment: CommentInfo) {
    const cont = await ElMessageBox.confirm(
      `确定要删除用户 "${comment.author.name}" 的评论吗？此操作不可恢复。`,
      '删除评论',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => true, () => false);
    
    if (!cont) return;
    
    const resp = await deleteComment(comment.id);
    if (resp.error) {
      ElMessage({ type: 'error', message: resp.error });
      return;
    }

    ElMessage({ type: 'success', message: '评论已删除' });
    this.update();
  }
}
</script>

<template>
  <admin-nav />
  <div class="comment-search-page">
    <h2>评论管理</h2>
    <div class="search-box">
      <el-input :model-value="keyword" @update:model-value="updateKeyword" placeholder="请输入评论关键词" class="search-input" />
    </div>
    <div v-if="comments?.comments.length" class="search-results">
      <el-table :data="comments.comments" style="width: 100%" v-loading="loading">
        <el-table-column label="评论作者" width="300">
          <template #default="{ row: { author } }: { row: CommentInfo }">
            <div class="user-info">
              <img :src="getAvatarUrl(author.avatar)" class="user-avatar" />
              <UserLink :user="author" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评论内容" min-width="300" show-overflow-tooltip>
          <template #default="{ row: { content } }: { row: CommentInfo }">
            <div class="comment-content">{{ content }}</div>
          </template>
        </el-table-column>
        <el-table-column label="小说" width="200" show-overflow-tooltip>
          <template #default="{ row: { novel } }: { row: CommentInfo }">
            <router-link :to="'novel/' + novel.id">{{ novel.title }}</router-link>
          </template>
        </el-table-column>
        <el-table-column label="章节" width="200" show-overflow-tooltip>
          <template #default="{ row: { chapter, novel } }: { row: CommentInfo }">
            <router-link :to="{ path: `novel/${novel.id}/chapter/${chapter.id}` }">{{ chapter.title }}</router-link>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" width="180">
          <template #default="{ row: { created_at } }: { row: CommentInfo }">
            {{ dayjs(created_at).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteComment(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无搜索结果" />
        </template>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="query.page"
          v-model:page-size="query.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="comments?.total || 0"
          layout="total, sizes, prev, pager, next"
        />
      </div>
    </div>
  </div>
</template>

<style scoped>
.comment-search-page {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.search-input {
  width: 500px;
}

.search-results {
  margin-top: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.comment-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: end;
}

:deep(.el-table a) {
  color: var(--el-color-primary);
  text-decoration: none;
}

:deep(.el-table a:hover) {
  text-decoration: underline;
}

:deep(.el-button--danger) {
  padding: 4px 8px;
}

:deep(.el-button--danger.is-disabled) {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
